import { MqttAsync } from '@ohos/mqtt';
import hilog from '@ohos.hilog';
import LinkedList from '@ohos.util.LinkedList';

export class MqttUtil {
  public static mqttAsyncClient;
  /**
   * 连接至MQTT服务器
   */
  public static connect() {
    this.mqttAsyncClient = MqttAsync.createMqtt({
      url: "180.107.140.223:1883",
      clientId: "e5fatos4jh3l79lndb0bs",
      persistenceType: 1,
    })

    let options = {
      //set userName and password
      userName: "zjl",
      password: "123456789a",
      connectTimeout: 1000,
      version: 0,
    };
    this.mqttAsyncClient.connect(options, (err, data) => {
      // to do Something
      console.info("anran-connect-err" + err);
      console.info("anran-connect-data" + JSON.stringify(data));
    });
    this.mqttAsyncClient.messageArrived((err, data) => {
      // to do Something
      console.info("anran-messageArrived-err" + err);
      console.info("anran-messageArrived-data" + JSON.stringify(data));
    });

  }

  /**
   * 发送消息请求
   */
  public static publish(topic: string, payload: string) {
    let publishOption = {
      topic: topic,
      qos: 1,
      payload: payload,
    }
    this.mqttAsyncClient.publish(publishOption, (err, data) => {
      // to do Something
      console.info("anran-publish-err" + err);
      console.info("anran-publish-data" + JSON.stringify(data));
    });
  }

  // 订阅主题。
  public static subscribe(topic: String) {
    let subscribeOption = {
      topic: topic,
      qos: 2
    }

    console.info("anran-subscribe-topic" + subscribeOption.topic);
    MqttUtil.mqttAsyncClient.subscribe(subscribeOption, (err, data) => {
      // to do Something
      console.info("anran-subscribe-err" + err);
      console.info("anran-subscribe-data" + JSON.stringify(data));
    });
  }

  /**
   * 事件回调
   * @param messageArrived
   */
  public static messageArrived(messageArrived: (err, data) => void) {
    this.mqttAsyncClient.messageArrived(messageArrived)
  }

  /**
   * 取消订阅
   */
  public static unsubscribe(topic: string) {
    let subscribeOption = {
      topic: topic,
      qos: 2
    }
    this.mqttAsyncClient.unsubscribe(subscribeOption)
  }
}